import storage from '@/utils/goodStorageUtil'
import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw } from 'vue-router'
const ctgy = () => import('@/piniaviews/ctgy/index.vue')
const books = () => import('@/piniaviews/books/index.vue')
const test = () => import('@/piniaviews/test/index.vue')
const bookDetail = () => import('@/piniaviews/bookDetail/index.vue')
const shopcartlist = () => import('@/piniaviews/shopcartlist/index.vue')
const search = () => import('@/piniaviews/search/index.vue')
const login = () => import('@/piniaviews/login-register/login/index.vue')

const routes: RouteRecordRaw[] = [
  {
    name: 'ctgy',
    path: '/ctgy',
    component: ctgy,
  },
  {
    name: 'search',
    path: '/search',
    component: search,
  },
  {
    name: 'books',
    path: '/books/:thirdctgyid',
    component: books,
  },
  {
    name: 'test',
    path: '/test',
    component: test,
  },
  {
    name: 'bookDetail',
    path: '/bookDetail/:id',
    component: bookDetail,
  },
  {
    name: 'shopcartlist',
    path: '/shopcartlist',
    component: shopcartlist,
  },
  {
    name: 'login',
    path: '/login',
    component: login,
    beforeEnter(to, from, next) {
      const token = storage.get('token')
      if (token) {
        next({ name: 'ctgy' })
      } else {
        next()
      }
    },
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

router.beforeEach((to, from, next) => {
  const token = storage.get('token')
  if (token || to.name === 'login') {
    next()
  } else {
    next({ name: 'login' })
  }
})

export default router
